<?php

namespace App\Admin\Controllers;

use App\Models\BookModel;
use App\Models\CompanyReadModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use App\Models\CompanyModel;
use Illuminate\Support\Facades\Auth;
use App\Models\CompanyReadBook;

class CompanyReadController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '企业读书管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new CompanyReadModel());

        $grid->column('id', __('Id'));
        //$grid->column('personal_title', '企业读书活动标题');
        $grid->column('company_id', '公司')->display(function ($company_id) {

            return CompanyModel::where('id',$company_id)->value('company_name');
        });

        $grid->column('title', '标题')->style('display:table-cell;vertical-align:middle;text-align:center;');

        //$grid->column('start_time', '开始时间')->style('display:table-cell;vertical-align:middle;text-align:center;');

        $grid->column('created_at','创建时间');
        $grid->column('updated_at', '更新时间');

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(CompanyReadModel::findOrFail($id));

        $show->field('id', __('Id'));
        //$show->field('personal_title', '企业读书活动标题');
        $show->field('company_id', '创建企业名称');
       // $show->field('book_id','书本名称');
        $show->field('created_at','创建时间');
        $show->field('updated_at', '更新时间');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new CompanyReadModel());

        $form->hidden('id','id');
        $form->select('company_id', '公司')->options(
            CompanyModel::where('status',3)->pluck('company_name','id')
        );

        $form->image('cove_url', '封面图')
            ->move('/upload/images/'.date('Ymd'));

        $form->text('title', '企业读书名称');

        $form->listboxsortable('book','綁定书本')->options(BookModel::pluck('book_title', 'id'));

        //保存后回调
        $form->saved(function (Form $form) {

            $book = $form->book;

            foreach ($book as $k=>$v){
                CompanyReadBook::where('comapny_read_id',$form->model()->id)->where('book_id',$v)->update([
                    'sort'=>$k+1
                ]);
            }

        });
        return $form;
    }
}
